<?php

namespace App\Transformers;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class SimpleTransformer extends BaseTransformer
{
    protected $only = [];

    /**
     * SimpleTransformer constructor.
     * @param array $only
     */
    public function __construct(array $only = [])
    {
        $this->only = $only;
    }

    public function transform($data)
    {
        return collect($this->only)->mapWithKeys(function ($kv, $kk) use ($data) {
            $key = is_numeric($kk) ? $kv : $kk;
            $value = $data->$key;
            if ($value instanceof Model) {
                throw new \Exception('请不要这样使用，很容易触发 N+1 性能问题');
            } elseif ($value instanceof Carbon) {
                $value = $value->toDateTimeString();
            }
            return [
                $kv => $value
            ];
        })->toArray();
    }

}